package com.muyu.system.controller;

import com.muyu.common.core.domain.Result;
import com.muyu.common.core.enums.SysNormalDisableEnum;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.core.web.controller.BaseController;
import com.muyu.common.log.annotation.Log;
import com.muyu.common.log.enums.BusinessType;
import com.muyu.common.security.annotation.RequiresPermissions;
import com.muyu.common.system.domain.SysDept;
import com.muyu.system.domain.model.CheckDeptNameUniqueModel;
import com.muyu.system.domain.model.SysDeptPageQueryModel;
import com.muyu.system.domain.req.SysDeptAddReq;
import com.muyu.system.domain.req.SysDeptListReq;
import com.muyu.system.domain.req.SysDeptUpdReq;
import com.muyu.system.service.SysDeptService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.muyu.common.core.constant.SplitConstants.COMMA_STR;

/**
 * 部门信息
 *
 * @author muyu
 */
@RestController
@RequestMapping("/dept")
@Tag(name = "SysDeptController", description = "部门管理")
public class SysDeptController extends BaseController {

    @Autowired
    private SysDeptService deptService;

    /**
     * 获取部门列表
     */
    @RequiresPermissions("system:dept:list")
    @PostMapping("/list")
    public Result<List<SysDept>> list (@RequestBody SysDeptListReq sysDeptListReq) {
        List<SysDept> deptList = deptService.queryList(SysDeptPageQueryModel.reqBuild(sysDeptListReq));
        return success(deptList);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public Result<List<SysDept>> excludeChild (@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> deptList = deptService.queryList(SysDeptPageQueryModel.builder().build());
        deptList.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), COMMA_STR), deptId));
        return success(deptList);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @RequiresPermissions("system:dept:query")
    @GetMapping(value = "/{deptId}")
    public Result<SysDept> getInfo (@PathVariable("deptId") Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @RequiresPermissions("system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<String> add (@Validated @RequestBody SysDeptAddReq sysDeptAddReq) {
        if (deptService.checkDeptNameUnique(CheckDeptNameUniqueModel.of(sysDeptAddReq.getDeptName()))) {
            return error("新增部门'" + sysDeptAddReq.getDeptName() + "'失败，部门名称已存在");
        }
        deptService.insertDept(sysDeptAddReq.buildSysDept());
        return success();
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{deptId}")
    public Result<String> edit (@PathVariable("deptId")Long deptId, @Validated @RequestBody SysDeptUpdReq sysDeptUpdReq) {
        deptService.checkDeptDataScope(deptId);
        if (deptService.checkDeptNameUnique(
                CheckDeptNameUniqueModel.of(sysDeptUpdReq.getDeptName(), deptId, sysDeptUpdReq.getParentId())
        )) {
            return error("修改部门'" + sysDeptUpdReq.getDeptName() + "'失败，部门名称已存在");
        } else if (sysDeptUpdReq.getParentId().equals(deptId)) {
            return error("修改部门'" + sysDeptUpdReq.getDeptName() + "'失败，上级部门不能是自己");
        } else if (SysNormalDisableEnum.isDisable(sysDeptUpdReq.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return error("该部门包含未停用的子部门！");
        }
        deptService.updateDept(sysDeptUpdReq.buildSysDept(deptId));
        return success();
    }

    /**
     * 删除部门
     */
    @RequiresPermissions("system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public Result<String> remove (@PathVariable("deptId") Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        deptService.deleteDeptById(deptId);
        return success();
    }
}
